﻿using MimeKit;
using MimeKit.Text;
using System;
using System.IO;

namespace CoreHelper
{
    /// <summary>
    /// 邮件发送帮助类
    /// 参考地址：https://blog.51cto.com/u_15057811/4321955
    /// MailKit开源地址：​https://github.com/jstedfast/MailKit​​ 文档：​http://www.mimekit.net/docs/​
    /// </summary>
    public class EmailHelper
    {
        #region 属性及变量
        //Nuget包管理添加Mailkit
        /// <summary>
        /// 服务器smtp
        /// </summary>
        private string _STEPNAME = "smtp.qq.com";
        /// <summary>
        /// 服务邮箱端口
        /// </summary>
        private int _STEPPORT = 587;
        /// <summary>
        /// 发送方邮箱地址
        /// </summary>
        private string _USEREMAIL;
        /// <summary>
        /// 发送方邮箱Smtp授权码
        /// </summary>
        private string _PASSWORD;
        /// <summary>
        /// 发送方邮箱归属人，昵称
        /// </summary>
        private string _EMAILBLONGER;
        #endregion

        #region 构造函数
        /// <summary>
        /// 邮箱配置
        /// </summary>
        /// <param name="email">发送方邮箱地址</param>
        /// <param name="smtp">发送方邮箱Smtp授权码</param>
        public EmailHelper(string email, string smtp)
        {
            this._USEREMAIL = email;
            this._PASSWORD = smtp;
        }

        /// <summary>
        /// 邮箱配置
        /// </summary>
        /// <param name="email">发送方邮箱地址</param>
        /// <param name="emailBlonger">发送方邮箱归属人，昵称</param>
        /// <param name="smtp">发送方邮箱Smtp授权码</param>
        public EmailHelper(string email, string emailBlonger, string smtp)
        {
            this._USEREMAIL = email;
            this._PASSWORD = smtp;
            this._EMAILBLONGER = emailBlonger;
        }
        #endregion

        #region 邮件发送单个
        /// <summary>
        /// 邮件发送单个
        /// </summary>
        /// <param name="toEmaill">接收方邮箱</param>
        /// <param name="toEmailBlonger">接收方名称</param>
        /// <param name="subject">邮件标题</param>
        /// <param name="text">发送的文字内容，html参数有内容时忽略此值</param>
        /// <param name="html">发送的html内容</param>
        /// <param name="path">发送的附件,找不到的就自动过滤</param>
        /// <returns></returns>
        public string SendEmail(string toEmaill, string toEmailBlonger, string subject, string text, string html = "", string path = "")
        {
            try
            {
                MimeMessage message = new MimeMessage();
                //发送方
                message.From.Add(new MailboxAddress(this._EMAILBLONGER, this._USEREMAIL));
                //接受方
                message.To.Add(new MailboxAddress(toEmailBlonger, toEmaill));
                //标题
                message.Subject = subject;
                //创建附件
                var multipart = new Multipart("mixed");
                //文字内容
                if (!string.IsNullOrEmpty(text))
                {
                    var plain = new TextPart(TextFormat.Plain)
                    {
                        Text = text
                    };
                    multipart.Add(plain);
                }
                //html内容
                if (!string.IsNullOrEmpty(html))
                {
                    var Html = new TextPart(TextFormat.Html)
                    {
                        Text = html
                    };
                    multipart.Add(Html);
                }
                if (!string.IsNullOrEmpty(path))
                {
                    var pathList = path.Split(';');
                    foreach (var p in pathList)
                    {
                        try
                        {
                            if (!string.IsNullOrEmpty(p.Trim()))
                            {
                                var attimg = new MimePart()
                                {
                                    //"image", "png"方法里带参数的话
                                    Content = new MimeContent(File.OpenRead(p), ContentEncoding.Default),
                                    ContentDisposition = new MimeKit.ContentDisposition(MimeKit.ContentDisposition.Attachment),
                                    ContentTransferEncoding = ContentEncoding.Base64,
                                    FileName = Path.GetFileName(path)
                                };
                                multipart.Add(attimg);
                            }
                        }
                        catch (FileNotFoundException ex)
                        {
                            LogHelper.Error("发送邮件失败", LogHelper.logsSource.其他, "EmailHelper", ex);
                            //找不到文件就不提交附件了
                        }
                    }
                }
                //赋值邮件内容
                message.Body = multipart;
                //开始发送
                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    client.Connect(this._STEPNAME, this._STEPPORT, false);
                    client.Authenticate(this._USEREMAIL, this._PASSWORD);
                    client.Send(message);
                    client.Disconnect(true);
                }
                return "0";//"邮件发送成功";
            }
            catch (Exception)
            {
                return "1";// "邮箱发送失败";
            }
        }
        #endregion

        #region 邮件发送单个，不用输入用户昵称的
        /// <summary>
        /// 邮件发送单个，不用输入用户昵称的
        /// </summary>
        /// <param name="toEmaill">接收方邮箱</param>
        /// <param name="subject">邮件标题</param>
        /// <param name="text">发送的文字内容，html参数有内容时忽略此值</param>
        /// <param name="html">发送的html内容</param>
        /// <param name="path">发送的附件路径，多附件用;隔开</param>
        /// <returns></returns>
        public string SendEmail(string toEmaill, string subject, string text, string html = "", string path = "")
        {
            try
            {
                MimeMessage message = new MimeMessage();
                //发送方
                message.From.Add(new MailboxAddress("系统邮件", this._USEREMAIL));
                //接收方
                message.To.Add(new MailboxAddress(toEmaill, toEmaill));

                //标题
                message.Subject = subject;
                //创建附件
                var multipart = new Multipart("mixed");
                //文字内容
                if (!string.IsNullOrEmpty(text))
                {
                    var plain = new TextPart(TextFormat.Plain)
                    {
                        Text = text
                    };
                    multipart.Add(plain);
                }
                //html内容
                if (!string.IsNullOrEmpty(html))
                {
                    var Html = new TextPart(TextFormat.Html)
                    {
                        Text = html
                    };
                    multipart.Add(Html);
                }
                if (!string.IsNullOrEmpty(path))
                {//修改为多附件，
                    var pathList = path.Split(';');
                    foreach (var p in pathList)
                    {
                        try
                        {
                            if (!string.IsNullOrEmpty(p.Trim()))
                            {
                                var attimg = new MimePart()
                                {
                                    //"image", "png"方法里带参数的话
                                    Content = new MimeContent(File.OpenRead(p), ContentEncoding.Default),
                                    ContentDisposition = new MimeKit.ContentDisposition(MimeKit.ContentDisposition.Attachment),
                                    ContentTransferEncoding = ContentEncoding.Base64,
                                    FileName = Path.GetFileName(path)
                                };
                                multipart.Add(attimg);
                            }
                        }
                        catch (FileNotFoundException ex)
                        {
                            LogHelper.Error("发送邮件失败", LogHelper.logsSource.其他, "EmailHelper", ex);
                            //找不到文件就不提交附件了
                        }
                    }
                }
                //赋值邮件内容
                message.Body = multipart;
                //开始发送
                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    client.Connect(this._STEPNAME, this._STEPPORT, false);
                    client.Authenticate(this._USEREMAIL, this._PASSWORD);
                    client.Send(message);
                    client.Disconnect(true);
                }
                return "0";//"邮件发送成功";
            }
            catch (Exception ex)
            {
                return ex.Message;// "邮箱发送失败";
            }
        }
        #endregion

        #region 邮件发送批量，不用输入用户昵称的
        /// <summary>
        /// 邮件发送批量，不用输入用户昵称的
        /// </summary>
        /// <param name="toEmailList">接收方邮箱,多个收件人用逗号隔开，但收件人会看到所有收到邮件的人的邮箱地址，体验不好</param>
        /// <param name="subject">邮件标题</param>
        /// <param name="text">发送的文字内容，html参数有内容时忽略此值</param>
        /// <param name="html">发送的html内容</param>
        /// <param name="path">发送的附件路径，多附件用;隔开</param>
        /// <returns></returns>
        public string SendBatchEmail(string toEmailList, string subject, string text, string html = "", string path = "")
        {
            try
            {
                MimeMessage message = new MimeMessage();
                //发送方
                message.From.Add(new MailboxAddress("系统邮件", this._USEREMAIL));
                //接收方
                var emaillist = toEmailList.Split(',');
                foreach (var item in emaillist)
                {
                    message.To.Add(new MailboxAddress(item, item));
                }

                //标题
                message.Subject = subject;
                //创建附件
                var multipart = new Multipart("mixed");
                //文字内容
                if (!string.IsNullOrEmpty(text))
                {
                    var plain = new TextPart(TextFormat.Plain)
                    {
                        Text = text
                    };
                    multipart.Add(plain);
                }
                //html内容
                if (!string.IsNullOrEmpty(html))
                {
                    var Html = new TextPart(TextFormat.Html)
                    {
                        Text = html
                    };
                    multipart.Add(Html);
                }
                if (!string.IsNullOrEmpty(path))
                {//修改为多附件，
                    var pathList = path.Split(';');
                    foreach (var p in pathList)
                    {
                        try
                        {
                            if (!string.IsNullOrEmpty(p.Trim()))
                            {
                                var attimg = new MimePart()
                                {
                                    //"image", "png"方法里带参数的话
                                    Content = new MimeContent(File.OpenRead(p), ContentEncoding.Default),
                                    ContentDisposition = new MimeKit.ContentDisposition(MimeKit.ContentDisposition.Attachment),
                                    ContentTransferEncoding = ContentEncoding.Base64,
                                    FileName = Path.GetFileName(path)
                                };
                                multipart.Add(attimg);
                            }
                        }
                        catch (FileNotFoundException ex)
                        {
                            LogHelper.Error("发送邮件失败", LogHelper.logsSource.其他, "EmailHelper", ex);
                            //找不到文件就不提交附件了
                        }
                    }
                }
                //赋值邮件内容
                message.Body = multipart;
                //开始发送
                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    client.Connect(this._STEPNAME, this._STEPPORT, false);
                    client.Authenticate(this._USEREMAIL, this._PASSWORD);
                    client.Send(message);
                    client.Disconnect(true);
                }
                return "0";//"邮件发送成功";
            }
            catch (Exception ex)
            {
                LogHelper.Error("发送邮件失败", LogHelper.logsSource.其他, "EmailHelper", ex);
                return "1";// "邮箱发送失败";
            }
        }
		#endregion


		#region 中原卡通，html模板1，仿阿里云证书到期通知
		/// <summary>
		/// html模板1，仿阿里云证书到期通知
		/// </summary>
		/// <param name="messagehtml">可能会经常更改的内容</param>
		/// <returns></returns>
		public string htmltemplate1(string messagehtml)
        {
            string _html = "<center><table align=\"left\" width=\"960\" style=\"font-family:'Microsoft YaHei';margin:10px 0 10px 0;background-color:#fff;color:#333333;border:1px solid #edecec;\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td>" +
                    "<div>" +
                    "<table width=\"960\" border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\" bgcolor=\"#373d41\" height=\"48\">" +
                    "<tbody><tr>" +
                    "<td width=\"174\" height=\"48\" border=\"0\" align=\"left\" valign=\"middle\" style=\"font-size:16px;font-weight:bold;color:#F5F4F4;padding-left:20px;height:48px;\">" +
                    "<span>中原卡通</span>" +
                    "</td>" +
                    //"<td width=\"703\" height=\"48\" colspan=\"2\" align=\"right\" valign=\"middle\" style=\"color:#ffffff; padding-right:20px;height:48px;\"><a href=\"http://babyai.cn\" target=\"_blank\" style=\"color:#ffffff;text-decoration:none;font-family:'Microsoft YaHei';\" rel=\"noopener\">幼儿人工智能(babyAI)</a>&nbsp;&nbsp; <span style=\"color:#6c7479;\">|</span>&nbsp;&nbsp;<a href=\"http://sigmall.cn\" target=\"_blank\" style=\"color:#ffffff;text-decoration:none;font-family:'Microsoft YaHei';\" rel=\"noopener\">政府采购(商城)</a>&nbsp;&nbsp; <span style=\"color:#6c7479;\">|</span>&nbsp;&nbsp;<a href=\"https://edu.chinasigma.cn/\" target=\"_blank\" style=\"color:#ffffff;text-decoration:none;font-family:'Microsoft YaHei';\" rel=\"noopener\">职业技能培训</a>&nbsp;&nbsp;</td>" +
                    "</tr></tbody></table>" +
                    "</div>" +

                    $"<div style=\"background:#FFF;padding:20px;text-align:left;\">{messagehtml}</div>" +

                    //"<table width=\"100%\" border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\" style=\"font-size:14px;color:#333333;\">" +
                    //"<tbody>" +
                    ////"<tr><td height=\"14\" style=\"padding:10px 0 16px 20px; border-bottom:1px dashed #e5e5e5;font-family:'Microsoft YaHei';\">联系电话：400-600-4080</td></tr>" +
                    //"<tr><td height=\"14\" style=\"padding:8px 0 18px 20px;color:#999999; font-size:12px;font-family:'Microsoft YaHei';\">此为系统自动邮件请勿回复</td></tr>" +
                    //"<tr><td style=\"width:800px;margin:0 auto; background-color: #181818;padding: 26px 0 20px 0\"><img style=\"padding-left:16px;vertical-align: middle;\" height=\"63px\" src=\"https://easy100-01-9g1cijo8432551a3-1332364215.tcloudbaseapp.com/mingpian/adimg/search2.png\"><span style=\"color: #ffffff;font-family:'Microsoft YaHei';font-size: 12px;margin: 0 0 0 230px; vertical-align: middle;\">Copyright © 金扬网络科技 2024 All Right Reserved</span></td></tr>" +
                    //"</tbody></table>" +

                    //<img style=\"padding-left:36px;vertical-align: middle;\" height=\"113px\" src=\"https://wmp.secondlife.net.cn/images/zhiyejinengtishenggzh.png\"><img style=\"padding-left:36px;vertical-align: middle;\" height=\"113px\" src=\"https://wmp.secondlife.net.cn/images/sigmallgzh.png\">

                    //"<table width=\"100%\" height=\"100\" border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\"><tbody>" +
                    //"<tr>" +
                    //"<td width=\"960\" height=\"100\" align=\"center\" valign=\"middle\" style=\"background-color:#F5F5F4;\">" +
                    //"<img border=\"0\" height=\"120\" src=\"https://img.alicdn.com/imgextra/i4/O1CN01nnae2B1lDZpApZUTa_!!6000000004785-2-tps-1600-240.png\">" +
                    //"</td>" +
                    //"</tr>" +
                    //"</tbody></table>" +

                    "<table align=\"center\" border=\"0\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" bgcolor=\"#fff\">" +
                    "<tbody><tr>" +
                    "<td>" +
                    //"<p style=\"line-height: 22px; font-family: 'Microsoft YaHei'; font-size: 12px; color: #999; text-align: center;\">"如果您不想再接收阿里云的「产品到期通知」邮件，或者需要设置其他人接收，点此<a href=\"https://account.aliyun.com/login/login.htm?&amp;msctype=email&amp;mscareaid=cn&amp;mscsiteid=cn&amp;mscmsgid=6900121102900468419&amp;oauth_callback=https%3a%2f%2fnotifications.console.aliyun.com%2f%23%2fsubscribeMsg%3fmessageTypeId%3dprod_msg_expire\" target=\"_blank\" style=\"text-decoration:none; color:#00a2ca;\" rel=\"noopener\">设置订阅。</a></p>" +
                    "</td>" +
                    "</tr>" +
                    "</tbody></table>" +
                    "</td></tr></tbody></table></center>";
            return _html;
        }
        #endregion

        #region html模板2，仿阿里云语雀通知
        /// <summary>
        /// 仿阿里云语雀通知
        /// </summary>
        /// <param name="messagehtml">邮件内容</param>
        /// <returns></returns>
        public string htmltemplate2(string messagehtml)
        {
            string _html = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" align=\"center\" style=\"border-collapse:collapse;width:460px;\">" +
                "<tbody><tr><td><div style=\"padding: 16px 0;text-align: center;\"><span style=\"font-size:24px; line-height: 36px; margin-top: 12px;\">语雀</span></div></td></tr>" +

                "<tr><td style=\"padding: 0;\">" +
                "<div style=\"border:1px solid #efefef; border-radius: 4px; padding: 0;\">" +
                "<img src=\"https://gw.alipayobjects.com/mdn/rms_5c2a0d/afts/img/A*MRlwQIYTl7EAAAAAAAAAAABjARQnAQ\" width=\"460\">" +
                "<div style=\"padding: 0 32px 32px;\">" +
                "<div style=\"font-size:24px; line-height: 36px; margin-top: 12px;\">欢迎使用空间</div>" +
                "<div style=\"padding: 8px 0\">" +

                "<p><strong></strong> 你好，你已开通 <strong>中原卡通</strong> 空间，在这里可以和空间成员一起完成知识创作与分享，体验全新的体系化知识管理。</p>" +
                "<p style=\"border-top: 1px solid #efefef;margin: 8px 0;\"></p>" +
                "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" align=\"center\" width=\"100%\">" +
                "<tbody><tr>" +
                "<td height=\"28\">空间地址：</td>" +
                "<td align=\"right\"><a href=\"\" target=\"_blank\"></a></td>" +
                "</tr>" +
                "<tr>" +
                "<td height=\"28\">人员上限：</td>" +
                "<td align=\"right\"><strong>人</strong></td>" +
                "</tr>" +
                "</tbody></table>" +

                "</div>" +
                "<div style=\"padding: 16px 0;border-top: 1px solid #efefef;\">" +
                "<div>如有疑问，请联系：<a href=\"mailto:support@yuque.com\" rel=\"noopener\" target=\"_blank\">support@yuque.com</a></div>" +
                "</div>" +
                "</div>" +
                "</div>" +
                "</td></tr>" +

                "<tr><td align=\"center\" style=\"padding: 16px 0;\">" +
                "<p>如需帮助，请查看 <a href=\"https://yuque.com/yuque\" target=\"_blank\" rel=\"noopener\">帮助文档</a></p>    " +
                "</td></tr>" +
                "</tbody></table>";
            return _html;
        }
        #endregion


        #region 调用方法
        //public class Test
        //{
        //    private email=new EmailHelper("发送方邮箱地址","Smtp授权码");
        //    email.SendEmail("对方的邮箱地址", "对方邮箱名称也可以是邮箱", "标题", "内容", "<b>这是html标记的文本</b>", "发送的附件路径，多附件用;隔开")
        //} 
        #endregion
    }
}
